<template>
    <drawer
      class="edit-SLA"
      :title="drawTitle"
      :drawer="drwaShow"
      size="520px"
      @cancelFun="cancelFun"
      @closeDraw="cancelFun"
      @save="save"
    >
      <template slot="column">
        <el-form class="m7-form" ref="form" :model="form" :rules="rules" label-position="top" size="small">
          <el-form-item label="SLA名称" prop="name">
            <el-input v-model="form.name" placeholder="请填写SLA名称" :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" :rows="5" placeholder="请填写描述" type="textarea" :maxlength="200"></el-input>
          </el-form-item>
          <el-form-item label="开始条件" prop="startCondition">
            <el-select class="select" v-model="form.startCondition.triggerEvent" placeholder="请选择" @change="handleStartTriggerEventChange">
              <el-option
                v-for="item in conditionList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择生效范围">
            <el-select
              style="display:block"
              v-model="form.startCondition.node"
              placeholder="请选择"
              filterable
              clearable
              :disabled="form.startCondition.triggerEvent === 3 || form.startCondition.triggerEvent === 4"
            >
              <el-option
                v-for="item in nodeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="结束条件" prop="endCondition">
            <el-select class="select" v-model="form.endCondition.triggerEvent" placeholder="请选择" @change="handleEndTriggerEventChange">
              <el-option
                v-for="item in conditionList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择生效范围">
            <el-select
              style="display:block"
              v-model="form.endCondition.node"
              placeholder="请选择"
              filterable
              :disabled="form.endCondition.triggerEvent === 3 || form.endCondition.triggerEvent === 4"
            >
              <el-option
                v-for="item in nodeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时效设置" prop="timeLimitedConfigList">
            <div class="line"></div>
            <div class="aging-setting" v-for="(item, index) in form.timeLimitedConfigList" :key="index">
              <i class="el-icon-remove" v-if="form.timeLimitedConfigList.length > 1" @click="delTimeLimitedConfigListT(index)"></i>
              <div>当满足</div>
              <conditionForm
                :fieldsList="filterFieldList"
                :conditonList="item.effectFilters"
                class="condition"
                type="filter"
              >
              </conditionForm>
              <div class="effective-indicators">
                <div class="time-title effective-indicators-title">计时规则</div>
                <el-select class="select" v-model="item.timingRule.timingRuleId" placeholder="请选择">
                  <el-option
                    v-for="item in timingRule"
                    :key="item._id"
                    :label="item.name"
                    :value="item._id">
                  </el-option>
                </el-select>
              </div>
              <div class="time-title">处理时长设置</div>
              <div class="timing-rules">
                <el-input v-model="item.timingRule.daySum" type="number" :min="0" :max="99" @change="handleDaySum($event, item)">
                  <div class="rules-end" slot="suffix">天</div>
                </el-input>
                <el-input v-model="item.timingRule.hourSum" type="number" :max="23" :min="0" @change="handleHourSum($event, item)">
                  <div class="rules-end" slot="suffix">小时</div>
                </el-input>
                <el-input v-model="item.timingRule.minuteSum" type="number" :max="59" :min="0" @change="handleMinuteSum($event, item)">
                  <div class="rules-end" slot="suffix">分钟</div>
                </el-input>
              </div>
              <div>
                <el-checkbox v-model="item.timingRule.dateTarget">是否允许具体时间为准</el-checkbox>
                <el-tooltip popper-class="tooltip-class"  placement="bottom">
                  <div slot="content" style="width:200px">启用该选项，当匹配SLA后，所选的日期类型字段有明确的时间点，则以该时间点为考核标准，若所选的日期字段类型为空，则还是以处理时长作为考核标准</div>
                  <i class="V7_iconfont V7_iconV7tubiao_bangzhu-42" style="color:#B3B9C7; font-size:12px;margin-left:8px"></i>
                </el-tooltip>
                <el-select style="display:block" v-if="item.timingRule.dateTarget" v-model="item.timingRule.fieldSimple.businessId" placeholder="选择日期类型字段" clearable>
                  <el-option
                    v-for="item in modelFields"
                    :key="item.businessId"
                    :label="item.name"
                    :value="item.businessId">
                  </el-option>
                </el-select>
              </div>
              <div class="time-title">超时提醒</div>
              <div class="timeout" v-for="(one, i) in item.timeoutRuleConfig.timeoutRuleList" :key="i">
                <el-select class="timeout-item" v-model="one.sendTimeType" placeholder="请选择">
                  <el-option
                    v-for="item in timeoutList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-input class="timeout-item" v-model="one.minuteCount" type="number" :min="0" :max="59" @change="handleTimeoutMinuteCount($event, one)">
                  <div class="rules-end" slot="suffix">分钟</div>
                </el-input>
                <optionalScope
                  class="timeout-item member"
                  :isTileDept="true"
                  :isCheckbox="true"
                  :tabs="optionTabs"
                  :collapseTags="true"
                  :value="one"
                ></optionalScope>
                <i class="el-icon-remove-outline timeout-del" @click="delTimeoutRuleList(item.timeoutRuleConfig.timeoutRuleList, i)"></i>
              </div>
              <div style="color: #008BEE">
                <i class="el-icon-plus"></i>
                <el-button  type="text" @click="addTimeout(item)">添加提醒</el-button>
              </div>
              <div class="time-title effective-indicators-title">选择发送渠道</div>
              <el-checkbox-group v-model="item.timeoutRuleConfig.sendTypeList">
                <el-checkbox :label="1">站内信通知</el-checkbox>
                <el-checkbox :label="2">企业微信</el-checkbox>
                <el-checkbox :label="3">短信</el-checkbox>
              </el-checkbox-group>
              <div v-if="item.timeoutRuleConfig.sendTypeList.indexOf(3) > -1" class="sms-block">
              <div class="msg-templ">
                <el-select
                  style="margin-right: 12px"
                  v-model="item.timeoutRuleConfig.smsSignId"
                  placeholder="选择签名"
                  filterable
                >
                  <el-option
                    v-for="item in smsSignList"
                    :key="item.id"
                    :label="item.displayName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <el-select
                  v-model="item.timeoutRuleConfig.smsTemplateId"
                  placeholder="选择模版"
                  filterable
                >
                  <el-option
                    v-for="item in smsTemplList"
                    :key="item.id"
                    :label="item.displayName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </div>
              <div class="sms-text" v-if="item.timeoutRuleConfig.sendTypeList.indexOf(3) > -1">
                <template v-if="getSmsSignMap[item.timeoutRuleConfig.smsSignId]">【{{getSmsSignMap[item.timeoutRuleConfig.smsSignId].displayName}}】</template>
                <template v-if="getSmsTemplMap[item.timeoutRuleConfig.smsTemplateId]">{{getSmsTemplMap[item.timeoutRuleConfig.smsTemplateId].content}}</template>
              </div>
            </div>
            </div>
            <div style="color: #008BEE">
              <i class="el-icon-plus"></i>
              <el-button  type="text" @click="addTimeLimitedConfigList">添加</el-button>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <!-- <div class="more-btn">
        <el-button size="mini" @click="cancel">取消</el-button>
        <el-button size="mini" type="primary" @click="save">保存</el-button>
      </div> -->
    </drawer>
</template>
<script lang="ts">
import { Component, Vue, Ref, Prop } from 'vue-property-decorator'
import { commonAction, deepClone } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import conditionForm from '@/afterSales/components/conditionFilter/conditionForm.vue'
import conditionFilter from '@/afterSales/components/conditionFilter/index.vue'
import drawer from '@/common/views/drawer/index.vue'
import optionalScope from '@/afterSales/views/config/serviceConfig/components/optionalScope.vue'

@Component({
  name: 'editSLA',
  components: {
    conditionForm,
    drawer,
    conditionFilter,
    optionalScope
  }
})

export default class extends Vue {
  @Prop({ default: () => [] }) private smsSignList
  @Prop({ default: () => [] }) private smsTemplList
  @Prop({ default: 0 }) private operateStatus!: number // 0 编辑 1 新增 2 复制
  @Prop({ default: '' }) private modelId!: string
  [x: string]: any

  private get userList () {
    return (CommonModule as any).publicCache.userList
  }

  public drwaShow: boolean = false
  private drawTitle: string = '新增SLA'
  private originForm = {}
  private form = {
    id: '',
    name: '',
    description: '',
    startCondition: {
      triggerEvent: 1,
      node: ''
    },
    endCondition: {
      triggerEvent: 1,
      node: ''
    },
    timeLimitedConfigList: [
      {
        timingRule: { // 计时规则
          cyclePeriods: [
            {
              days: [],
              timePoint: []
            }
          ],
          daySum: 0,
          hourSum: 0,
          minuteSum: 0,
          dateTarget: false,
          timingRuleId: '',
          fieldSimple: {
            businessId: '',
            fieldType: 'dateTime'
          }
        },
        timeoutRuleConfig: { // 超时提醒
          smsSignId: '',
          smsTemplateId: '',
          sendTypeList: [], // 发送渠道; 1 站内信，2 企业微信，3 短信
          timeoutRuleList: [
            {
              keyList: [],
              memberIdList: [], // 成员id
              memberTypeList: [], // 发送人员类型; 1 成员，2 动态
              minuteCount: 1,
              sendTimeType: 1 // 1 超时前，2 超时后
            }
          ]
        },
        effectFilters: [] // 生效指标条件
      }
    ]
  }

  private get getSmsTemplMap () {
    const obj = {};
    this.smsTemplList.map((item) => {
      obj[item.id] = item;
    });
    return obj;
  }

  private get getSmsSignMap () {
    const obj = {};
    this.smsSignList.map((item) => {
      obj[item.id] = item;
    });
    return obj;
  }

  private timingRule: any[] = []
  private nodeList: any[] = []
  private modelFields: any[] = []
  private filterFieldList: any[] = []
  private optionTabs: any[] = [
    {
      name: '成员',
      type: 'memberIdList',
      list: this.userList,
      listMap: (CommonModule as any).publicCache.userListObj,
      defaultProps: { id: '_id', name: 'agentName' }
    },
    {
      name: '动态',
      type: 'keyList',
      list: [],
      listMap: {},
      defaultProps: { id: 'businessId', name: 'name' }
    }
  ]

  private rules = {
    name: [
      { required: true, message: '请填写SLA名称', trigger: 'blur' }
    ],
    startCondition: [
      { required: true, message: '请选择开始条件', trigger: 'change' }
    ],
    endCondition: [
      { required: true, message: '请选择结束条件', trigger: 'change' }
    ],
    timeLimitedConfigList: [
      { required: true, trigger: 'change' }
    ]
  }

  private conditionList = [
    {
      label: '工单进入节点',
      value: 1
    },
    {
      label: '工单离开节点',
      value: 2
    },
    {
      label: '工单终止',
      value: 3
    },
    {
      label: '工单完成',
      value: 4
    },
    {
      label: '工单被转派',
      value: 5
    },
    {
      label: '工单被领取',
      value: 6
    }
  ]

  private timeoutList = [
    {
      label: '超时前提醒',
      value: 1
    },
    {
      label: '超时后提醒  ',
      value: 2
    }
  ]

  private validTimingRule (rule, value, callback) {
    const flag = value.some(item => item.timingRule.timingRuleId === '')
    if (flag) {
      this.$message.error('计时规则不能为空')
    } else {
      callback()
    }
  }

  private handleStartTriggerEventChange (val) {
    if (val === 3 || val === 4) {
      this.form.startCondition.node = ''
    }
  }

  private handleEndTriggerEventChange (val) {
    if (val === 3 || val === 4) {
      this.form.endCondition.node = ''
    }
  }

  private handleDrawerOpen () {
    if (this.operateStatus === 1) {
      // (this.$refs.form as any).resetFields()
      this.form = {
        id: '',
        name: '',
        description: '',
        startCondition: {
          triggerEvent: 1,
          node: ''
        },
        endCondition: {
          triggerEvent: 1,
          node: ''
        },
        timeLimitedConfigList: [
          {
            timingRule: { // 计时规则
              cyclePeriods: [
                {
                  days: [],
                  timePoint: []
                }
              ],
              daySum: 0,
              hourSum: 0,
              minuteSum: 0,
              dateTarget: false,
              timingRuleId: '',
              fieldSimple: {
                businessId: '',
                fieldType: 'dateTime'
              }
            },
            timeoutRuleConfig: { // 超时提醒
              smsSignId: '',
              smsTemplateId: '',
              sendTypeList: [], // 发送渠道; 1 站内信，2 企业微信，3 短信
              timeoutRuleList: [
                {
                  keyList: [],
                  memberIdList: [], // 成员id
                  memberTypeList: [], // 发送人员类型; 1 成员，2 动态
                  minuteCount: 1,
                  sendTimeType: 1 // 1 超时前，2 超时后
                }
              ]
            },
            effectFilters: [] // 生效指标条件
          }
        ]
      }
    }
  }

  public setForm (val) {
    this.drwaShow = true
    this.$nextTick(() => {
      this.form = deepClone(val)
      if (this.operateStatus === 2) {
        this.form.name = val.name + '-副本'
      }
      this.drawTitle = this.form.name
    })
  }

  public resetForm () {
    this.drawTitle = '新增SLA'
    this.drwaShow = true
    this.handleDrawerOpen()
  }

  private cancel () {
    this.drwaShow = false
  }

  private checkNumber (val, min, max) {
    if (val < min || val > max) {
      this.$message.warning(`请输入${min}到${max}的数字`)
      return true
    } else {
      return false
    }
  }

  private handleDaySum (val, formVal) {
    if (this.checkNumber(val, 0, 99)) {
      formVal.timingRule.daySum = 0
    }
  }

  private handleHourSum (val, formVal) {
    if (this.checkNumber(val, 0, 23)) {
      formVal.timingRule.hourSum = 0
    }
  }

  private handleMinuteSum (val, formVal) {
    if (this.checkNumber(val, 0, 59)) {
      formVal.timingRule.minuteSum = 0
    }
  }

  private handleTimeoutMinuteCount (val, formVal) {
    if (this.checkNumber(val, 1, 59)) {
      formVal.minuteCount = 0
    }
  }

  private getTimeLimitedConfigList (val) {
    return val.map(item => {
      const timeingRuleObj = this.timingRule.find(one => one._id === item.timingRule.timingRuleId)
      if (timeingRuleObj) {
        item.timingRule.cyclePeriods = timeingRuleObj.cyclePeriods
      }
      if (item.timingRule.dateTarget === false) {
        delete item.timingRule.fieldSimple
      }
      item.timeoutRuleConfig.timeoutRuleList.forEach(one => {
        one.memberTypeList = []
        if (one.memberIdList.length) {
          one.memberTypeList.push(1)
        }
        if (one.keyList.length) {
          one.memberTypeList.push(2)
        }
      })
      return item
    })
  }

  private savaSLA () {
    const { name, description, startCondition, endCondition, timeLimitedConfigList } = this.form

    const postData: any = {
      description,
      name,
      modelId: this.modelId,
      startCondition,
      endCondition,
      timeLimitedConfigList: this.getTimeLimitedConfigList(timeLimitedConfigList)
    }
    commonAction({
      url: '/server-work/action/sla/config/insert',
      method: 'post',
      data: postData
    }).then(res => {
      if (res.success) {
        this.$message.success('添加成功')
        this.drwaShow = false
        this.$emit('refresh-list')
      }
    })
  }

  private updateSLA () {
    const { name, description, startCondition, endCondition, timeLimitedConfigList, id } = this.form
    const postData: any = {
      description,
      name,
      id,
      modelId: this.modelId,
      startCondition,
      endCondition,
      timeLimitedConfigList: this.getTimeLimitedConfigList(timeLimitedConfigList)
    }
    commonAction({
      url: '/server-work/action/sla/config/update',
      method: 'post',
      data: postData
    }).then(res => {
      if (res.success) {
        this.$message.success('修改成功')
        this.drwaShow = false
        this.$emit('refresh-list')
      }
    })
  }

  private save () {
    (this.$refs.form as any).validate(valid => {
      if (valid) {
        const flag = this.form.timeLimitedConfigList.some(item => item.timingRule.timingRuleId === '')
        const exactTime = this.form.timeLimitedConfigList.some(item => item.timingRule.dateTarget && !item.timingRule.fieldSimple.businessId)
        const nameLength = this.form.name.length
        const time = this.form.timeLimitedConfigList.some(item => !(item.timingRule.daySum || item.timingRule.hourSum || item.timingRule.minuteSum))
        const start = this.form.startCondition.triggerEvent !== 3 && this.form.startCondition.triggerEvent !== 4 && !this.form.startCondition.node
        const end = this.form.endCondition.triggerEvent !== 3 && this.form.endCondition.triggerEvent !== 4 && !this.form.endCondition.node
        const remind = this.form.timeLimitedConfigList.some(item => {
          return item.timeoutRuleConfig.timeoutRuleList.some(x => x.minuteCount < 1 || x.minuteCount > 59)
        })
        if (flag) {
          this.$message.error('计时规则不能为空')
        } else if (exactTime) {
          this.$message.error('日期类型字段不能为空')
        } else if (nameLength > 20) {
          this.$message.error('名称不能超过20个字符')
        } else if (time) {
          this.$message.error('处理时长不能全为0')
        } else if (start) {
          this.$message.error('开始条件生效范围不能为空')
        } else if (end) {
          this.$message.error('结束条件生效范围不能为空')
        } else if (remind) {
          this.$message.error('超时提醒时间为1到59')
        } else {
          if (this.operateStatus) {
            // 插入
            this.savaSLA()
          } else {
            this.updateSLA()
          }
        }
      }
    })
  }

  private addTimeout (val) {
    val.timeoutRuleConfig.timeoutRuleList.push({
      memberIdList: [],
      memberTypeList: [],
      minuteCount: 1,
      sendTimeTpye: 1,
      keyList: []
    })
  }

  private addTimeLimitedConfigList () {
    this.form.timeLimitedConfigList.push(
      {
        timingRule: { // 计时规则
          cyclePeriods: [
            {
              days: [],
              timePoint: []
            }
          ],
          daySum: 0,
          hourSum: 0,
          minuteSum: 0,
          dateTarget: false,
          timingRuleId: '',
          fieldSimple: {
            businessId: '',
            fieldType: 'dateTime'
          }
        },
        timeoutRuleConfig: { // 超时提醒
          smsSignId: '',
          smsTemplateId: '',
          sendTypeList: [], // 发送渠道; 1 站内信，2 企业微信，3 短信
          timeoutRuleList: [
            {
              keyList: [],
              memberIdList: [], // 成员id
              memberTypeList: [], // 发送人员类型; 1 成员，2 动态
              minuteCount: 1,
              sendTimeType: 1 // 1 超时前，2 超时后
            }
          ]
        } as any,
        effectFilters: [] // 生效指标条件
      }
    )
  }

  private delTimeLimitedConfigListT (index) {
    this.form.timeLimitedConfigList.splice(index, 1)
  }

  private delTimeoutRuleList (val, index) {
    val.splice(index, 1)
  }

  private getTimeSetting () {
    commonAction({
      url: '/base/action/config/timecondition/query',
      method: 'post',
      data: { limit: 50, page: 1, name: '', types: ['cycle'] }
    }).then(res => {
      if (res.success) {
        this.timingRule = res.list
      }
    })
  }

  private fetchNodeList () {
    commonAction({ url: '/server-flow/action/definition/userTask?modelId=' + this.$route.params.businessId, method: 'get' }).then(res => {
      if (res.success) {
        this.nodeList = res.data
      }
    })
  }

  private getWorkerOrderConfig () {
    commonAction({
      url: '/server-work/action/workOrderModel/getConfig',
      method: 'post',
      data: { modelId: this.modelId, queryFieldType: 1 }
    }).then(res => {
      if (res.success) {
        const fieldType = ['text', 'multiText', 'radio', 'IntegerList', 'number', 'dateTime', 'member', 'department', 'accessory', 'cascadeSelect']
        this.filterFieldList = res.data.fields.filter(item => {
          return fieldType.includes(item.fieldType) && !item.isSystem
        })
        this.modelFields = res.data.fields.filter(item => item.fieldType === 'dateTime' && !item.isSystem)
        this.optionTabs[1].list = res.data.fields.filter(item => (item.fieldType === 'member' && item.businessId !== 'updateUser') || (item.businessId === 'master'))
        this.optionTabs[1].list.forEach((item) => {
          this.optionTabs[1].listMap[item.businessId] = item
        })
      }
    })
  }

  private cancelFun () {
    this.drwaShow = false
  }

  private created () {
    this.getTimeSetting()
    this.fetchNodeList()
    this.getWorkerOrderConfig()
  }
}
</script>
<style lang="stylus" scoped>
.sms-block
  background: #FBFBFB;
  border-radius: 4px;
  padding: 16px;
.sms-text {
  font-weight: 400;
  font-size: 12px;
  line-height: 18px;
  margin-top: 8px;
}
.msg-templ {
  display: flex;
}
.edit-SLA
  /deep/.el-form-item__label
    font-size 14px
    font-weight 500
  /deep/.el-drawer__body
    height: 100%
  .select
    width 100%
  .more-btn
    position absolute
    right 24px
  .m7-form
    // padding: 0 24px
    // height: calc(100% - 130px)
    // overflow: auto
    .line
      border-bottom: 1px solid #F2F3F4;
      position: relative;
      top: -4px;
  .aging-setting
    background: #FBFBFB
    padding 24px 12px
    margin-top 12px
    position relative
    font-size 12px
    line-height: 1
    .time-title
      margin 24px 0 8px 0
    .effective-indicators-title
      margin 15px 0 8px 0
    .el-icon-remove:hover
      color #008BEE
    .el-icon-remove
      position: absolute;
      right: -5px;
      top: -7px;
      color #02010180
  .rules-end
    line-height 32px
  .timing-rules
    display flex
    margin-bottom 8px
    /deep/.el-input
      margin 0 5px
  .timeout
    display flex
    .member
      // /deep/.el-input__inner
      //   position relative
      //   top 5px
    .timeout-item
      margin 0 5px
      width 100%
    .timeout-del
      line-height: 32px
      cursor pointer
      color #B3B9C7
</style>
